﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PrototypeZGame
{
    public abstract class Controller
    {
        public Unit unit;
        protected World world;
        protected Terrain terrain;
        public Actor target;
        protected List<Direction> path;

        public Controller(World world)
        {
            this.world = world;
            this.terrain = world.terrain;
        }

        public virtual void Posses(Unit _unit)
        {
            if (unit != null)
            {
                unit.UnPossesed();
                unit = null;
            }            
            _unit.PossesedBy(this);
            unit = _unit;
        }

        public virtual void UnPosses()
        {
            unit = null;
        }

        public virtual void newTurn()
        {
            if (unit == null) return;
            unit.newTurn();
        }


        protected virtual Result walk(Direction direction)
        {
            return unit.walk(direction);
        }


        public virtual string getInfoString()
        {
            if (unit == null) return "No unit";
            else return unit.getInfoString();
        }

        public Vec2 getUnitPos()
        {
            return unit.position;
        }

        public abstract void UnitDied();


        protected Result MoveToTarget(int searchDistance)
        {
            Vec2 S = unit.position;
            Vec2 A = new Vec2(S.x - searchDistance, S.y - searchDistance);
            Vec2 B = new Vec2(S.x + searchDistance + 1, S.y + searchDistance + 1);
            Vec2 D = target.position;

            path = Dijskra.getPath(terrain, S, D, A, B);

            if (path != null)
            {
                return walk(path[0]);
            }
            else
            {
                return Result.NoPath;
            }
        }

        public override string ToString()
        {
            string ret = "";
            if(target != null)
            {
                ret += "Target = " + target.name + "\n";
            }
            return ret;
        }
    }
}
